//
//  YFDayRecordItem.m
//  PaddleTennisDemo
//
//  Created by Coollang on 2017/10/13.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFDayRecordItem.h"
#import "YFSwingDetailItem.h"
#import "NSString+Extension.h"
#import "DeviceInfo.h"
#import <DateTools/DateTools.h>

@implementation YFDayRecordItem

+ (NSArray<NSString *> *)ignoredProperties {
    return @[@"sportTimeInterval"];
}

+ (NSString *)primaryKey {
    return @"identification";
}

- (void)dayRecordItemFormDeviceDict:(NSDictionary *)dict {
    self.userId = [User getLastUser].userID;
    self.dateTimeStamp = [dict[@"dateTimeStamp"] longLongValue];
    self.dayDate = [NSDate timeWithTimeIntervalString: self.dateTimeStamp];
    self.identification = [NSString stringWithFormat:@"%@_%@",self.userId,self.dayDate];
    self.exerciseTimeInterval = [dict[@"exerciseTimeInterval"] integerValue];
    // 用于显示同步进度
    self.dayAmountOfCount = [dict[@"dayAmountOfCount"] integerValue];
    DeviceInfo *device = [DeviceInfo getLastDevice];
    self.deviceMac = device.macAddress;
    self.firewareVersion = device.locationVersion;
    self.locationUpdateTime = kCurrentDateTime;
}

- (void)dayRecordItemFormServerDict:(NSDictionary *)dict {
    self.dayDate = dict[@"Date"];
    self.userId = dict[@"UserID"];
    self.identification = [NSString stringWithFormat:@"%@_%@",self.userId,self.dayDate];
    self.dateTimeStamp = [[NSDate formateYearMonthDayString:[User getUseInfo].createTime] timeIntervalSince1970];
    self.dayCalories = [dict[@"Caroline"] floatValue];
    self.exerciseTimeInterval = [dict[@"Duration"] integerValue];
    self.maxSwingSpeed = [dict[@"MaxSpeed"] integerValue];
    self.maxStrength = [dict[@"MaxStrength"] integerValue];
    self.avgSpeed = [dict[@"AvgSpeed"] integerValue];
    self.avgStrength = [dict[@"AvgStrength"] integerValue];
    self.foreHandCount = [dict[@"ForeHand"] integerValue];
    self.dayAmountOfCount = [dict[@"Swings"] integerValue];
    self.sweetHitTimes = [dict[@"SweetHitTimes"] integerValue];
    self.firewareVersion = dict[@"FirmwareVersion"];
    self.deviceMac = dict[@"Mac"];
    self.serverUpdateTime = [dict[@"UploadTime"] integerValue];
//    self.isSyncToServer = YES;
    self.isSyncDetialToServer = YES;
    self.locationUpdateTime = [dict[@"UploadTime"] integerValue];
}



// 数据上传到服务器
- (NSDictionary *)dayRecordItemToDict {
    NSDictionary *dictT = @{
                            @"Date":self.dayDate,
                            @"Swings":@(self.dayAmountOfCount).stringValue,
                            @"Caroline":@(self.dayCalories),
                            @"Duration":@(self.exerciseTimeInterval).stringValue,
                            @"ForeHand":@(self.foreHandCount).stringValue,
                            @"BackHand":@(self.dayAmountOfCount - self.foreHandCount).stringValue,
                            @"SweetHitTimes":@(self.sweetHitTimes).stringValue,
                            @"AvgStrength":@(self.avgStrength).stringValue,
                            @"AvgSpeed":@(self.avgSpeed).stringValue,
                            @"MaxSpeed":@(self.maxSwingSpeed).stringValue,
                            @"MaxStrength":@(self.maxStrength).stringValue,
                            @"UploadTime":@(self.locationUpdateTime),// 更新的时间戳
                            };
    return dictT;
}

// 获取当前用户所有的天统计数据
+ (RLMResults *)getUserAllDayRecordItems {
    return [YFDayRecordItem objectsWhere:@"userId == %@",[User getLastUser].userID];
}

/**
 * 将天的统计数据存入用户数据库
 */
+ (void)saveDayRecoedItemToDocument:(YFDayRecordItem *)dayRecord update:(BOOL)update {
    if (dayRecord.identification == nil || dayRecord.userId == nil) {
        return;
    }
    YFThreeDTemplate *templateItem = [YFThreeDTemplate objectForPrimaryKey:dayRecord.identification];
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    if (templateItem == nil) {
        [realm addObject:dayRecord];
    }else {
        if (update) {
            [realm addOrUpdateObject:dayRecord];
        }
    }
    [realm commitWriteTransaction];
}

#pragma mark - 添加详情数据
/**
 * 添加详情数据
 * 注意：详情数据的时间戳可能会重复
 * update: YES 当已存在是覆盖旧值，NO 当已存在时不存入数据库
 */
- (BOOL)addDetailItem:(YFSwingDetailItem *)detailItem isUpdate:(BOOL)update {
    [[RLMRealm defaultRealm] beginWriteTransaction];
    RLMResults *result = [self.detailItems objectsWithPredicate:[NSPredicate predicateWithFormat:@"indentation == %@",detailItem.indentation]];
    BOOL have = NO;
    if (result.count == 0) {
        [self.detailItems addObject:detailItem];
        have = NO;
    }else {
        if (update) {
            NSInteger index = [self.detailItems indexOfObject:result.firstObject];
            [self.detailItems replaceObjectAtIndex:index withObject:detailItem];
        }
        have = YES;
    }
    [[RLMRealm defaultRealm] commitWriteTransaction];
    return have;
}

- (void)addDetailItems:(NSArray *)detailItems isOpenTransaction:(BOOL)openTransaction {
    if (openTransaction) {
        [[RLMRealm defaultRealm] beginWriteTransaction];
    }
    [detailItems enumerateObjectsUsingBlock:^(YFSwingDetailItem *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RLMResults *result = [self.detailItems objectsWithPredicate:[NSPredicate predicateWithFormat:@"indentation == %@",obj.indentation]];
        if (result.count == 0) {
            [self.detailItems addObject:obj];
        }else {
            NSInteger index = [self.detailItems indexOfObject:result.firstObject];
            [self.detailItems replaceObjectAtIndex:index withObject:obj];
        }
    }];
    if (openTransaction) {
        [[RLMRealm defaultRealm] commitWriteTransaction];
    }
//    [self calculateStatisticsValue];
}

// 根据详情数据计算统计数据
- (void)calculateStatisticsValue {
    self.dayAmountOfCount = self.detailItems.count;
    
    self.maxSwingSpeed = [[self.detailItems maxOfProperty:@"swingSpeed"] integerValue];
    self.avgSpeed = [[self.detailItems averageOfProperty:@"swingSpeed"] integerValue];
    
    self.maxStrength = [[self.detailItems maxOfProperty:@"strength"] integerValue];
    self.avgStrength = [[self.detailItems averageOfProperty:@"strength"] integerValue];
    RLMResults *sweatResults = [self.detailItems objectsWithPredicate:[NSPredicate predicateWithFormat:@"areaValue >= 1 && areaValue <=4"]];
    self.sweetHitTimes = sweatResults.count;
    
    RLMResults *foreHandResults = [self.detailItems objectsWithPredicate:[NSPredicate predicateWithFormat:@"handType == %d",HandDirectionTypeForeward]];
    self.foreHandCount = foreHandResults.count;
    // 计算卡路里
    UserInfoItem *infoItem = [User getUseInfo];
    CGFloat sportTime = (self.sportTimeInterval / 60.0);
    if (sportTime != 0) {
       sportTime = sportTime > 0.1 ? sportTime:0.1;
    }
    self.dayCalories = [self calculateCaloriesWithGender:infoItem.gender age:infoItem.getAge weight:infoItem.weight.integerValue sportDuration:sportTime];
    self.locationUpdateTime = kCurrentDateTime;
}

- (NSInteger)sportTimeInterval {
    if (self.exerciseTimeInterval <= 0) {
        NSInteger totalSwingTime = round([[self.detailItems sumOfProperty:@"swingTime"] integerValue] * 0.001);
        return totalSwingTime;
    }else {
        return self.exerciseTimeInterval * 60;
    }
}

/**
 * 计算卡路里的公式
 * sportTime:运动时间/min
 */
- (CGFloat)calculateCaloriesWithGender:(Gender)gender age:(NSInteger)age weight:(NSInteger)weight sportDuration:(CGFloat)sportTime {
    
    CGFloat x1,x2;
    if (gender == GenderFemale) {
        if (age < 31) {
            x1 = 14.6;
            x2 = 450;
        } else if (age < 61) {
            x1 = 8.6;
            x2 = 830;
        } else {
            x1 = 10.4;
            x2 = 600;
        }
    }else {
        if (age < 31) {
            x1 = 15.2;
            x2 = 680;
        } else if (age < 61) {
            x1 = 11.5;
            x2 = 830;
        } else {
            x1 = 13.4;
            x2 = 490;
        }
    }
    NSInteger weightT = (weight > 300) ? 300:weight;
    CGFloat calories = (x1 * weightT + x2) * 0.4 * sportTime/60.0;
    return calories;
}

@end

/*
 - (instancetype)initWithFormDeviceDict:(NSDictionary *)dict {
 if (self = [super init]) {
 [self setValuesForKeysWithDictionary:dict];
 self.userId = [User getLastUser].userID;
 self.dayDate = [NSDate timeWithTimeIntervalString:self.dateTimeStamp];
 self.identification = [NSString stringWithFormat:@"%@%@",self.userId,self.dayDate];
 }
 return self;
 }
 - (id)valueForUndefinedKey:(NSString *)key {
 YFLog(@"KVC Error key:%@",key);
 return nil;
 }
 */
